<template >
  <div id="components-layout-demo-basic">
    <a-layout style="background-color: white ">
      <a-layout-header>
        <div class="head_group" style="margin: 0px;padding: 0px;">
          <a-button @click="back">返回</a-button>
          <a-button style="float:right;" @click="add" :disabled="isDisabled">添加</a-button>
        </div>
        <hr color="#00a0e9"/>
      </a-layout-header>

      <a-layout-content>
        <a-table
          :columns="columns"
          :data-source="awardsList"
          rowKey='id'
          :pagination="false"
          :scroll="{ y: heightTable }"
          size="middle"
          bordered>
          <template  slot="operation" slot-scope="text, record">
            <div style="text-align: center;">
              <a @click="handleEdit(record.id)" style="margin-right: 10px;" :disabled="isDisabled">编辑</a>
              <a type="danger"  @click="handleDelete(record.id)" :disabled="isDisabled">删除</a>
            </div>
          </template >
        </a-table>

        <a-modal
          :visible="visible"
          :confirm-loading="confirmLoading"
          @ok="handleOk"
          @cancel="handleCancel"
        >
          <div style="padding-top:30px;">
            <a-form-model ref="awards" :model="awards" :rules="rules">
              <a-row >
                <a-col :span="24">
                  <a-form-model-item
                    :label-col="formItemLayout.labelColModal"
                    :wrapper-col="formItemLayout.wrapperColModal"
                    label="获奖名称"
                    prop="prizeName"
                  >
                    <a-input v-model="awards.prizeName" type="text" size="large" placeholder="获奖名称" style="width: 100%;" :disabled="isDisabled"/>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row >
                <a-col :span="24">
                  <a-form-model-item
                    :label-col="formItemLayout.labelColModal"
                    :wrapper-col="formItemLayout.wrapperColModal"
                    label="获奖时间"
                    prop="prizeDate"
                  >
                    <a-date-picker v-model="awards.prizeDate" size="large" placeholder="选择日期" style="width: 100%;" :disabled="isDisabled"/>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="24">
                  <a-form-model-item
                    :label-col="formItemLayout.labelColModal"
                    :wrapper-col="formItemLayout.wrapperColModal"
                    label="形式"
                    prop="prizeForm"
                  >
                    <a-radio-group v-model="awards.prizeForm" name="radioGroup" :default-value="1" :disabled="isDisabled">
                      <a-radio v-for="(radioInfo,i) in radioList" :value="radioInfo.id" :key="radioInfo.id" >
                        {{radioInfo.name}}
                      </a-radio>
                    </a-radio-group>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row >
                <a-col :span="24">
                  <a-form-model-item
                    :label-col="formItemLayout.labelColModal"
                    :wrapper-col="formItemLayout.wrapperColModal"

                    label="附件"
                  >
                    <a-upload
                      :disabled="isDisabled"
                      :action="BASE_API+'awards/awards/upload'"
                      :default-file-list="defaultFileList"
                      :before-upload="beforeUpload"
                      @change="handleChange"
                    >
                      <a-button> <a-icon type="upload" /> 附件 </a-button>
                    </a-upload>
                  </a-form-model-item>
                </a-col>
              </a-row>

            </a-form-model>
          </div>
        </a-modal>

      </a-layout-content>

      <a-layout-footer style="background-color: white;">
        <a-pagination
          show-quick-jumper
          v-model="pagination.page"
          :page-size-options="pagination.pageSizeOptions"
          :total="pagination.total"
          show-size-changer
          :page-size="pagination.pageSize"
          @change="onChangePagination"
          @showSizeChange="onShowSizeChange"
        >
          <template slot="buildOptionText" slot-scope="props">
            <span v-if="props.value !== '100'">{{ props.value }}条/页</span>
            <!--            <span v-if="props.value === '50'">全部</span>-->
          </template>
        </a-pagination>

      </a-layout-footer>
    </a-layout>
  </div>
</template>

<script>

    import {getAction,postAction,putAction,deleteAction} from '@/api/manage'
    import {API} from '@/api/base_api';
    //布局占据的位数
    const formItemLayout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 12 },
        labelColModal: { span: 4 },
        wrapperColModal: { span: 18 },
    };
    const columns = [
        {
            title: '序列',
            dataIndex: 'serialNumber',
            width: '20%',
            scopedSlots: { customRender: 'serialNumber' },
        },
        {
            title: '获奖名称',
            dataIndex: 'prizeName',
            width: '20%',
            scopedSlots: { customRender: 'prizeName' },
        },
        {
            title: '获奖形式 ',
            dataIndex: 'prizeFormString',
            width: '20%',
            scopedSlots: { customRender: 'prizeFormString' },
        },
        {
            title: '获奖时间 ',
            dataIndex: 'prizeDateString',
            width: '20%',
            scopedSlots: { customRender: 'prizeDate' },
        },
        {
            title: '操作',
            dataIndex: 'operation',
            scopedSlots: { customRender: 'operation' },
        },
    ];


    //已占领的高度
    let occupyHeight = 400;

    export default {
        name: "Awards",
        data(){
            return{
                paneKey:1,
                //控件是否能编辑
                isDisabled:true,
                BASE_API:null,
                //modal弹窗
                visible: false,
                confirmLoading: false,
                //控件占一半位置
                widthLayout:{
                    width:'60%',
                },
                //默认上传的文件列表
                defaultFileList: [],
                //table高度
                heightTable:0,
                //布局占据的位数
                formItemLayout,
                //列表列
                columns,
                radioList:[],
                //数据列表
                awardsList:[],
                awards:{
                    prizeName:null,//获奖名称
                    prizeDate:null,//时间
                    prizeForm:null,//形式
                    accessory:null,//附件
                    basicId:null,
                },
                rules: {
                    prizeName: [
                        {required: true, message: '获奖名称不能为空', trigger: 'blur'},
                    ],
                    prizeDate:[
                        {required: true, message: '时间不能为空', trigger: 'change'},
                    ],
                    prizeForm:[
                        {required: true, message: '形式不能为空', trigger: 'blur'},
                    ]
                },
                //分页
                pagination: {
                    page:1,//当前页数
                    pageSize: 10,//每页中显示10条数据
                    total: 0,
                    showSizeChanger: true,
                    pageSizeOptions: ['10', '20', '30', '40', '50'],//每页中显示的数据
                    showTotal: total => `共有 ${total} 条数据`,  //分页中显示总的数据
                },
                //是否有基本信息
                isExists:false,
            }
        },
        // mounted() {
        //     //获取高度值
        //     window.onresize = () => {
        //         this.heightTable = document.documentElement.clientHeight-occupyHeight;
        //         console.log("awards = > tableHeight = ",this.heightTable)
        //     }
        // },
        methods:{
            //初始化
            init(){
                this.BASE_API = API();
                this.initPrizeForm();
                this.getList();
            },
            getList(){
                if(this.isExists){
                    let that =  this;
                    getAction(`/awards/awards/list/${that.pagination.page}/${that.pagination.pageSize}/${that.awards.basicId}`).then(res=>{
                        console.log("dataSource = ",res.result);
                        that.awardsList = res.result.records;
                        that.pagination.total = res.result.total;
                        that.pagination.page = res.result.current;
                        that.pagination.pageSize = res.result.size;
                    })
                }
            },
            initPrizeForm(){
                let that = this;
                getAction("/prizeform/prize-form/list").then(res=>{
                    that.radioList = res.result;
                })
            },
            //返回list页面
            back(){
                this.$emit('router-pane',this.paneKey,0)
            },
            reset(){
                this.awards.prizeName='';
                this.awards.prizeDate='';
                this.awards.prizeForm='';
                this.awards.accessory='';
            },
            //获取父组件中isDisable
            isDisable(isDisabled){
                this.isDisabled = isDisabled;
            },
            //添加数据
            add(){
                if(!this.isExists){
                    this.$message.info('不存在基本信息，请先填完基本信息保存后再填写！');
                    return;
                }
                this.reset();
                this.visible = true;
                //校验清除
                if(this.$refs.awards!=null){
                    this.$refs.awards.resetFields()
                }
            },
            //弹窗确认和取消
            handleOk(e) {
                let that = this;
                this.$refs.awards.validate(valid => {
                    if (valid) {
                        //保存   交给后端判断是保存还是更新，如果有id就是更新，没有就是保存
                        that.confirmLoading = true;
                        console.log("awards = >",that.awards);
                        postAction("/awards/awards/save",that.awards).then(res=>{

                            that.reset();
                            that.getList();
                            that.visible = false;
                            that.confirmLoading = false;
                        }).catch(res=>{
                            this.$message.warning('保存失败！');
                            that.confirmLoading = false;
                        })
                    } else {
                        this.$message.info('信息填写不完整，请填写完成再提交！');
                        return false;
                    }
                });
            },
            handleCancel(e) {
                // //校验清除
                if(this.$refs.awards!=null){
                    this.$refs.awards.resetFields()
                }
                this.reset();
                this.visible = false;
            },
            //编辑
            handleEdit(id ) {
                let that = this;
                this.reset();
                //校验清除
                if(this.$refs.awards!=null){
                    this.$refs.awards.resetFields()
                }
                getAction("/awards/awards/info/"+id).then(res=>{
                    that.visible = true;
                    that.awards = res.result;
                    console.log("professional = >",that.awards);
                    if(that.awards.accessory!=null&&that.awards.accessory!=""){
                        console.log("有附件！")
                        let name = that.awards.accessory.substring(that.awards.accessory.lastIndexOf("/")+1);
                        that.defaultFileList.length = 0;
                        that.defaultFileList.push({
                            uid: that.awards.id,
                            name: name,
                            status: 'done',
                            response: 'Server Error 500', // custom error message to show
                            url: this.awards.accessory
                        });
                    }else{
                        that.defaultFileList.length = 0;
                    }


                }).catch(res=>{
                    that.$message.warning('更新获取信息失败！');
                })
            },
            //删除
            handleDelete(id) {
                let that = this;
                this.$confirm({
                    title: '警告！',
                    content: '是否删除数据？',
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk() {
                        that.loading = true;
                        deleteAction("/awards/awards/delete/"+id).then(resp =>{
                            that.init();
                            console.log("删除数据完成",resp);
                            that.loading = false;
                        }).catch(error=>{
                            console.log("删除数据错误",error);
                        })
                    },
                    onCancel() {
                        console.log('Cancel');
                    },
                });
            },
            //上传文件
            handleChange(info) {
                if (info.file.status === 'uploading') {
                    this.loading = true;
                    return;
                }
                if (info.file.status === 'done') {
                    console.log("图片info = ",info)
                    this.awards.accessory = this.BASE_API + info.file.response.message;
                    this.loading = false;
                }
            },
            //上传文件前先判断条件是否满足
            beforeUpload(file) {
                const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                if (!isJpgOrPng) {
                    this.$message.error('请选择Jpeg格式或png格式的图片！');
                }
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.$message.error('图片不得超过2Mb!');
                }
                return isJpgOrPng && isLt2M;
            },
            //分页触发当前页
            onChangePagination(current){
                this.pagination.page = current;
                this.getList();
            },
            //分页大小
            onShowSizeChange(current, pageSize) {
                this.pagination.page = current;//当前页
                this.pagination.pageSize = pageSize;//页数大小
                this.getList();
            },
            //加载高度
            initLoadHeight(height,){
                this.heightTable = height-(occupyHeight);
            },
            initBasicId(basicId){
                if(basicId>0){
                    //已有基本信息，可以添加信息
                    this.isExists=true;
                    this.awards.basicId = basicId;
                    this.init();
                }else{
                    //还没有基本信息 ，无法添加其他信息
                    this.isExists=false;
                    this.awardsList = [];
                }
            }
        },
        created() {
            this.init();
        }
    }
</script>

<style scoped>



</style>